package com.example.e_comm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.e_comm.entity.User;
import com.example.e_comm.mapper.UserMapper;
import com.example.e_comm.service.UserService;
import com.example.e_comm.utils.RedisUtil;
import com.example.e_comm.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 用户服务实现类
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public boolean register(User user) {
        // 查重：username email
        if(this.count(new QueryWrapper<User>()
                .eq("username",user.getUsername()))>0){
            throw new IllegalArgumentException("用户名已存在,请替换其它用户名");
        }
        if(this.count(new QueryWrapper<User>()
                .eq("email",user.getEmail()))>0){
            throw new IllegalArgumentException("邮箱已被注册！");
        }
        if(user.getPassword()==null){
            throw new IllegalArgumentException("密码不能为空！");
        }
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        user.setStatus(1);
        return this.save(user);
    }

    @Override
    public String login(String username, String password) {
        //登录验证，验证是否正确输入username、password
        if (StringUtils.isEmpty(username)&&StringUtils.isEmpty(password)){
            throw new IllegalArgumentException("用户名或密码不能为空！");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();//用于实现查询条件对象
        //根据用户名、密码查询状态为在用的用户
        queryWrapper.eq("username",username)
                .eq("password",(DigestUtils.md5DigestAsHex(password.getBytes())))
                .eq("status",1);
        User user = this.getOne(queryWrapper);
        if (user == null) {
            throw new IllegalArgumentException("用户名或密码错误,请查证后重新操作");
        }
        //为找到用户生产Token
        String token = tokenUtil.generaToken();
        //将生成的Token保存到Redis缓存中，同时设定有效时长
        redisUtil.set("user:token:"+token,user.getId().toString(),30, TimeUnit.MINUTES);
        //建立用户Id与token的映射关系
        redisUtil.set("user:id:"+user.getId(),token,30,TimeUnit.MINUTES);
        return token;
    }
    //
    @Override
    public User getUserByToken(String token) {
        if (!tokenUtil.validateToken(token)) {
            return null;
        }
        Object userIdObj = redisUtil.get("user:token:" + token);
        if (userIdObj == null) {
            return null;
        }
        try {
            Long userId = Long.valueOf(userIdObj.toString());//获取Redis中的UserId
            //根据用户ID查DB
            User user = this.getById(userId);
            if (user != null) {
                //刷新token
                redisUtil.set("user:token:"+token,user.getId().toString(),30, TimeUnit.MINUTES);
                redisUtil.set("user:id:"+user.getId(),token,30,TimeUnit.MINUTES);
            }
            return user;
        } catch (Exception e) {
            System.err.println("没有找到与这个token适配的User" + e.getMessage());
        }
        return null;
    }
//    @Override
//    public User getUserByToken(String token) {
//        // 验证token有效性
//        if (!tokenUtil.validateToken(token)) {
//            return null;
//        }
//
//        // 从Redis获取用户ID
//        Object userIdObj = redisUtil.get("user:token:" + token);
//        if (userIdObj == null) {
//            return null;
//        }
//
//        try {
//            // 安全地转换用户ID
//            Long userId = Long.valueOf(userIdObj.toString());
//
//            // 根据用户ID查询数据库
//            User user = this.getById(userId);
//            if (user != null) {
//                // 刷新token有效期
//                redisUtil.set("user:token:" + token, user.getId().toString(), 30, TimeUnit.MINUTES);
//                redisUtil.set("user:id:" + user.getId(), token, 30, TimeUnit.MINUTES);
//            }
//            return user;
//        } catch (NumberFormatException e) {
//            System.err.println("Token对应的用户ID格式错误: " + e.getMessage());
//            return null;
//        } catch (Exception e) {
//            System.err.println("获取用户信息失败: " + e.getMessage());
//            return null;
//        }
//    }

    @Override
    public boolean logout(String token) {
        User user = getUserByToken(token);
        if(user != null){
            redisUtil.delete("user:token:"+token);
            redisUtil.delete("user:id:"+user.getId());
            return true;
        }
        return false;
    }
    public boolean validateToken(String token) {
        return redisUtil.hasKey("user:token:" + token);
    }

    @Override
    public List<User> getUsersByRoleId(Long roleId) {
        if (roleId == null || roleId <= 0) {
            return Collections.emptyList();
        }
        return userMapper.getUsersByRoleId(roleId);
    }

    @Override
    public User getUserByUsername(String username) {
        if (username == null || username.isEmpty()) {
            return null;
        }
        return userMapper.selectByUsername(username);
    }

    @Override
    public List<User> getUsersById(Long userId) {
        if (userId == null || userId <= 0) {
            return Collections.emptyList();
        }
        return userMapper.getUsersById(userId);
    }

    @Override
    public List<User> getUsersByIdSet(Set<Long> userIdSet) {
        if (userIdSet == null || userIdSet.isEmpty()) {
            return Collections.emptyList();
        }
        return userMapper.getUsersByIdSet(userIdSet);
    }
}

